package com.shujia.common_util.three;

/*
想要演示浅克隆的问题, 注释掉clone方法即可
 */
public class Teacher implements Cloneable {

    private String name;
    private int age;
    private Address address;


    // 异常的处理方法, 在方法的末尾添加  throws Exception
    public static void main(String[] args) throws Exception {
        Teacher teacher = new Teacher();
        teacher.name = "赵四";
        teacher.age = 11;
        Address address = new Address();
        address.setDetail("合肥市, 蜀山区, 英唐产业园");
        teacher.address = address;

        // 浅克隆 -> 深克隆
        Object obj = teacher.clone();
        Teacher cloneTea = (Teacher) obj;
        System.out.println(cloneTea.name);
        System.out.println(cloneTea.age);
        System.out.println(cloneTea.address.getDetail());


        // 浅克隆, 克隆的引用数据类型指向同一个堆内存的地址值
        System.out.println(System.identityHashCode(teacher.address));
        System.out.println(System.identityHashCode(cloneTea.address));

        // 修改原对象里面的属性值, 会同步印象克隆的对象的属性值
        teacher.address.setDetail("合肥市, 滨湖区, xxxx");
        System.out.println(cloneTea.address.getDetail());

        System.out.println(teacher.address.getDetail());
    }

    /*
    实现深克隆
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj = super.clone();
        Teacher teacher = (Teacher) obj;
        // 取出引用数据类型, 再次克隆
        Address address = teacher.address;
        // 克隆出来的Address就是一个新的对象
        Address newAddr = (Address) address.clone();

        teacher.address = newAddr;
        return teacher;
    }
}
